<template>

  <div class="app-container">

    <h2 style="text-align: center;">发布新课程</h2>

    <el-steps :active="1" process-status="wait" align-center style="margin-bottom: 40px;">
      <el-step title="填写课程基本信息"/>
      <el-step title="创建课程大纲"/>
      <el-step title="发布课程"/>
    </el-steps>
    <el-form label-width="120px">

      <el-form-item label="课程标题">
        <el-input v-model="courseInfo.title" placeholder=" 示例：机器学习项目课：从基础到搭建项目视频课程。专业名称注意大小写"/>
      </el-form-item>

      <!-- 所属分类：级联下拉列表 -->
      <!-- 一级分类 -->
      <el-form-item label="课程类别">
        <el-select
          @change="getChildrenSubject"
          v-model="courseInfo.subjectParentId"
          placeholder="请选择">
          <el-option
            v-for="subject in oneSubjectList"
            :key="subject.id"
            :label="subject.title"
            :value="subject.id"/>
        </el-select>
        <!-- 二级分类 -->
        <el-select v-model="courseInfo.subjectId" placeholder="请选择">
          <el-option
            v-for="subject in twoSubjectList"
            :key="subject.value"
            :label="subject.title"
            :value="subject.id"/>
        </el-select>
      </el-form-item>

      <!-- 课程讲师 -->
      <el-form-item label="课程讲师">
        <el-select
          v-model="courseInfo.teacherId"
          placeholder="请选择">
          <el-option
            v-for="teacher in teacherList"
            :key="teacher.id"
            :label="teacher.name"
            :value="teacher.id"/>
        </el-select>
      </el-form-item>

      <el-form-item label="总课时">
        <el-input-number :min="0" v-model="courseInfo.lessonNum" controls-position="right" placeholder="请填写课程的总课时数"/>
      </el-form-item>

      <!-- 课程简介-->
      <el-form-item label="课程简介">
        <tinymce :height="300" v-model="courseInfo.description"/>
      </el-form-item>

      <!-- 课程封面-->
      <el-form-item label="课程封面">
        <el-upload
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :action="BASE_API+'/oss/file/upload'"
          class="avatar-uploader">
          <img :src="courseInfo.cover">
        </el-upload>

      </el-form-item>

      <el-form-item label="课程价格">
        <el-input-number :min="0" v-model="courseInfo.price" controls-position="right" placeholder="免费课程请设置为0元"/>
        元
      </el-form-item>

      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="next">保存并下一步</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  const defaultForm = {
    courseId: 0,//课程id
    title: '',//课程标题
    subjectId: '',//课程所属分类
    subjectParentId: '',//课程所属父级id
    teacherId: '',//课程讲师
    lessonNum: 0,//课时数
    description: '',//课程简介
    cover: process.env.OSS_PATH + "/cover/1.jpg",//课程封面
    price: 0,//课程价格
  };
  import course from "@/api/teach/course";
  import subject from "@/api/teach/subject";
  import teacher from "@/api/teach/teacher";
  import Tinymce from '@/components/Tinymce'

  export default {
    components: {Tinymce},
    name: "courseInfo",
    data() {
      return {
        saveBtnDisabled: false,//保存按钮是否禁用
        courseInfo: defaultForm,//课程表单对象
        oneSubjectList: [],//一级分类列表
        twoSubjectList: [],//二级分类列表
        teacherList: [],//课程讲师
        BASE_API: process.env.BASE_API,//后端接口api地址
      }
    },
    watch: {//路由监听
      $route(to, from) {//路由发生变化，方法就会执行
        this.init()
      }
    },
    created() {
      this.init()
    },
    methods: {
      //上传成功后调用的方法
      handleAvatarSuccess(res, file) {
        console.log(res)
        //获取图片地址
        this.courseInfo.cover = res.data.url
      },
      //上传封面前-对文件进行校验
      beforeAvatarUpload(file) {
        console.log(file)
        const isJPG = file.type === 'image/jpeg'
        const isLt2M = file.size / 1024 / 1024 < 2

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
        }
        return isJPG && isLt2M
      },

      //初始化页面
      init() {
        //判断路径是否有id值
        if (this.$route.params && this.$route.params.id) {//有id值
          //获取路径id值，赋值给课程id值
          const id = this.$route.params.id
          //获取课程基本信息
          this.getCOurseById(id)
        } else {//初始化表单
          this.courseInfo = {...defaultForm};
          this.courseInfo.description = '';
          //初始化分类
          this.getSubjectList()
          //初始化讲师
          this.getTeacherList()
        }
      },
      //根据课程id获取课程信息
      getCOurseById(id) {
        course.getCourseByCourseId(id)
          .then(response => {//查询成功
            this.courseInfo = response.data.courseInfoForm;
            //初始化分类列表
            subject.querySubjectList()
              .then(response => {
                //获取后端返回数据
                this.oneSubjectList = response.data.subjectVoList
                //遍历一级分类
                for (let i = 0; i < this.oneSubjectList.length; i++) {
                  //判断查询出来的一级分类id和当前课程一级分类id是否相同
                  if (this.oneSubjectList[i].id === this.courseInfo.subjectParentId) {
                    //获取二级分类
                    this.twoSubjectList = this.oneSubjectList[i].children
                  }
                }
              })
            //初始化讲师列表
            this.getTeacherList()
          })
          .catch(response => {
            //提示
            this.$message({
              type: 'error',
              message: response.message
            })
          })
      },
      //下一步方法
      next() {
        //禁用保存按钮
        this.saveBtnDisabled = true;
        //判断是修改还是添加--根据课程对象中是否有课程id判断
        if (this.courseInfo.id) {
          //修改
          this.updateCourseById()
        } else {
          //添加
          //调用添加方法
          this.save()
        }
      },
      //修改的方法
      updateCourseById() {
        course.updateCourse(this.courseInfo)
          .then(response => {//修改成功
            //提示
            this.$message({
              type: 'success',
              message: response.message
            });
            return response//将返回结果传递给then
          })
          .then(response => {
            this.$router.push({path: '/teach/course/chapter/' + this.courseInfo.id})
          })
          .catch(response => {//保存失败
            //提示
            this.$message({
              type: 'error',
              message: response.message
            })
          })
      },
      //初始化讲师列表
      getTeacherList() {
        teacher.getList()
          .then(response => {
            this.teacherList = response.data.teacherList
          })
      },

      //初始化一级分类列表
      getSubjectList() {
        subject.querySubjectList()
          .then(response => {
            this.oneSubjectList = response.data.subjectVoList
          })
      },
      //点击一级分类时，显示对应二级分类,value就是点击的分类的Id
      getChildrenSubject(value) {
        //遍历一级分类
        for (let i = 0; i < this.oneSubjectList.length; i++) {
          //判断点击的一级分类id和二级分类id是否相同
          if (this.oneSubjectList[i].id === value) {
            //获取一级分类对应的二级分类
            this.twoSubjectList = this.oneSubjectList[i].children
            //清空表单对象的分类id
            this.courseInfo.subjectId = ''
          }
        }
      },
      //保存的方法
      save() {
        //调用api接口
        course.saveCourseInfo(this.courseInfo)
          .then(response => {//保存成功
            //提示
            this.$message({
              type: 'success',
              message: response.message
            })
            return response//将返回结果传递给then
          })
          .then(response => {
            this.$router.push({path: '/teach/course/chapter/' + response.data.courseId})
          })
          .catch(response => {//保存失败
            //提示
            this.$message({
              type: 'error',
              message: response.message
            })
          })
      }
    }
  }
</script>

<style scoped>
  .tinymce-container {
    line-height: 29px;
  }
</style>
